package JZ59_按之字形顺序打印二叉树;

import java.util.ArrayList;
import java.util.Stack;
import java.util.TreeSet;


class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}

public class Solution {
    public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> lists = new ArrayList<>();
        Stack<TreeNode> stack1 = new Stack<>();
        Stack<TreeNode> stack2 = new Stack<>();

        if (pRoot == null){
            return lists;
        }
        stack1.add(pRoot);
        while (stack1.size() > 0 || stack2.size() > 0){
            ArrayList<Integer> list = new ArrayList<>();
            if (stack1.size() > 0){
                int size = stack1.size();
                for (int i = 0; i < size; i++){
                    TreeNode pop = stack1.pop();
                    list.add(pop.val);
                    if (pop.left != null){
                        stack2.add(pop.left);
                    }
                    if (pop.right != null){
                        stack2.add(pop.right);
                    }
                }
                lists.add(list);
                continue;
            }

            if (stack2.size() > 0){
                int size = stack2.size();
                for (int i = 0; i < size; i++){
                    TreeNode pop = stack2.pop();
                    list.add(pop.val);
                    if (pop.right != null){
                        stack1.add(pop.right);
                    }
                    if (pop.left != null){
                        stack1.add(pop.left);
                    }
                }
                lists.add(list);
            }

        }
        return lists;
    }

}